﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Timer=System.Windows.Forms.Timer;
using msilgc.common;

namespace Demo {
    public partial class DemoForm : Form {
        public DemoForm() {
            InitializeComponent();
            this.GPUProgressBar.Enabled = false;
            this.CPUProgressBar.Enabled = false;
            ranges = new int[100][];
            for (int i = 0; i < ranges.Length; i++ )
            {
                ranges[i] = new[]{1000, 10000};
            }
        }

        private readonly int[][] ranges;
        private System.Windows.Forms.Timer timer;
        private int cudaDone;
        private int cpuDone;

        private void button1_Click(object sender, EventArgs e) {
            cudaDone = 0;
            cpuDone = 0;
            timer = new Timer();
            timer.Interval = 100;
            timer.Tick += timer_Tick;
            timer.Start();
            GPUProgressBar.Value = 0;
            GPUProgressBar.Minimum = 0;
            GPUProgressBar.Maximum = ranges.Length;
            CPUProgressBar.Value = 0;
            CPUProgressBar.Minimum = 0;
            CPUProgressBar.Maximum = ranges.Length;

            var method = TestMethods.Compile_TestPrimeCUDA();
            Thread t1 = new Thread(CudaThread);
            Thread t2 = new Thread(IntelThread);
            t1.IsBackground = true;
            t2.IsBackground = true;
            t1.Start(method);
            t2.Start();
        }

        public void timer_Tick(object sender, EventArgs e) {
            if(cudaDone == ranges.Length && cpuDone == ranges.Length) {
                timer.Stop();
                timer.Dispose();
                timer = null;
            }
            GPUProgressBar.Value = cudaDone;
            CPUProgressBar.Value = cpuDone;
        }

        private void CudaThread(object args) {
            var method = (IMethodHandle) args;
            for(int i = 0 ; i < ranges.Length; i++) {
                int[] range = ranges[0];
                TestMethods.TestPrime_CUDA(method, range[0], range[1]);
                cudaDone += 1;
            }
        }

        private void IntelThread()
        {
            for (int i = 0; i < ranges.Length; i++) {
                int[] range = ranges[0];
                TestMethods.TestPrime_Intel(range[0], range[1]);
                cpuDone += 1;
            }
        }
    }
}
